<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Newsclass;
use App\Models\Newspopedom;
use App\Models\Role;
use Illuminate\Http\Request;

class NewspopedomController extends Controller {

	public function __construct() {
		$this->middleware('role:system');
	}

	/**
	 * 进入资讯权限管理页面
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function getIndex(Request $request) {
		$role_id = to_limit_lng($request->input('role_id'), 1);
		$data['role_id'] = $role_id;
		$data['perms'] = Newspopedom::get_role_popedoms($role_id);
		$data['roles'] = Role::all();
		$data['columns'] = Newsclass::getTree();
		return view('admin/news/popedom', $data);
	}

	/**
	 * 增加权限
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function postAddPopedom(Request $request) {
		$role_id = intval($request->input('role_id'));
		$class_id = strval($request->input('class_id'));
		$popedom = intval($request->input('popedom'));

		if ($role_id == 1) {
			return $this->response('ok');
		}

		$row = Newspopedom::where('class_id', $class_id)->where('role_id', $role_id)->first();
		if (empty($row)) {
			$row = new Newspopedom;
			$row->class_id = $class_id;
			$row->role_id = $role_id;
			$row->popedom = $popedom;
			$row->save();
		} else {
			$query = Newspopedom::where(['class_id' => $class_id, 'role_id' => $role_id]);
			$query->update(['popedom' => $row->popedom | $popedom]);
		}
		return $this->response('ok');
	}

	/**
	 * 删除权限
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	public function postRemovePopedom(Request $request) {
		$role_id = intval($request->input('role_id'));
		$class_id = strval($request->input('class_id'));
		$popedom = intval($request->input('popedom'));

		if ($role_id == 1) {
			return $this->response('ok');
		}

		$query = Newspopedom::where(['class_id' => $class_id, 'role_id' => $role_id]);
		$row = $query->first();
		if (empty($row)) {
			return $this->error('Operation Failed.');
		}
		$val = $row->popedom ^ $popedom;
		if ($val == 0) {
			$query->delete();
		} else {
			$query->update(['popedom' => $val]);
		}
		return $this->response('ok');
	}

}
